package com.musictest;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.Nullable;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.HashMap;

import static android.content.Context.NOTIFICATION_SERVICE;

public class ToastModule extends ReactContextBaseJavaModule {

    private static final String DURATION_SHORT_KEY = "SHORT";
    private static final String DURATION_LONG_KEY = "LONG";

    private static final String MY_MEDIA_ROOT_ID = "TestPlay";
    private MediaSessionCompat mMediaSession;
    private PlaybackStateCompat.Builder stateBuilder;


    private NotificationManager nm;
    private RemoteViews contentViews;
    private Notification notify;
    private int NOTIFICATION_ID = 123;


    public ToastModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    private static ToastModule module;
    public static ToastModule getInstance(){
        return module;
    }

    @Override
    public String getName() {
        return "ToastExample";
    }


    @Override
    public Map<String, Object> getConstants() {
        final Map<String, Object> constants = new HashMap<>();
        constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
        constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
        return constants;
    }

    @ReactMethod
    public void initSession() {
        System.out.println("initSession开始");
        module = this;
        initNotification();
        try {
            mMediaSession = new MediaSessionCompat(getReactApplicationContext(), MY_MEDIA_ROOT_ID);
            //指明支持的按键信息类型
            mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
            //监听的事件（播放，暂停，上一曲，下一曲）
            stateBuilder = new PlaybackStateCompat.Builder()
                    .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE
                            | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS);
            mMediaSession.setPlaybackState(stateBuilder.build());
            //设置监听回调
            mMediaSession.setCallback(sessionCb);
            //必须设置为true，这样才能开始接收各种信息
            mMediaSession.setActive(true);

        } catch (Exception e) {
//            LogTool.ex(e);
        }
    }



    private void initNotification() {
        System.out.println("initNotification");
        //NotificationManager的获取
        nm = (NotificationManager)getReactApplicationContext().getSystemService(NOTIFICATION_SERVICE);
        Intent mainIntent = new Intent(getReactApplicationContext(), MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(getReactApplicationContext(), 0, mainIntent, 0);

        notify = new Notification();
        //通知显示时间
        notify.when = System.currentTimeMillis();
        notify.icon = R.drawable.musicfile;
        notify.contentIntent = pi;//点击通知跳转到MainActivity
        //FLAG_AUTO_CANCEL 表示该通知能被状态栏的清除按钮给清除掉
        notify.flags = Notification.FLAG_NO_CLEAR;

        //获取布局
        contentViews = new RemoteViews("com.musictest", R.layout.notification);
        //点击图标和标题都会进入app
        contentViews.setOnClickPendingIntent(R.id.playtag, pi);
        contentViews.setOnClickPendingIntent(R.id.currentmusic, pi);

        //上一首图标添加点击监听
        Intent previousButtonIntent = new Intent("com.musictest.broadcasttest.PREVIOUS");
        PendingIntent pendPreviousButtonIntent = PendingIntent.getBroadcast(getReactApplicationContext(), 0, previousButtonIntent, 0);
        contentViews.setOnClickPendingIntent(R.id.pre, pendPreviousButtonIntent);

        //播放/暂停添加点击监听
        Intent playPauseButtonIntent = new Intent("com.musictest.broadcasttest.PLAYANDPAUSE");
        PendingIntent playPausePendingIntent = PendingIntent.getBroadcast(getReactApplicationContext(), 0, playPauseButtonIntent, 0);
        contentViews.setOnClickPendingIntent(R.id.playandpause, playPausePendingIntent);

        //下一首图标添加监听
        Intent nextButtonIntent = new Intent("com.musictest.broadcasttest.NEXT");
        PendingIntent pendNextButtonIntent = PendingIntent.getBroadcast(getReactApplicationContext(), 0, nextButtonIntent, 0);
        contentViews.setOnClickPendingIntent(R.id.next, pendNextButtonIntent);

        //退出监听
        Intent exitButton = new Intent("com.musictest.broadcasttest.EXIT");
        PendingIntent pendingExitButtonIntent = PendingIntent.getBroadcast(getReactApplicationContext(),0,exitButton,0);
        contentViews.setOnClickPendingIntent(R.id.close,pendingExitButtonIntent);

//        showNotification(true);
    }

    @ReactMethod
    private void showNotification(boolean isPlaying) {
        System.out.println("showNotification");

        if(isPlaying){
            contentViews.setImageViewResource(R.id.playandpause,android.R.drawable.ic_media_pause);
        }
        else{
            contentViews.setImageViewResource(R.id.playandpause,android.R.drawable.ic_media_play);
        }
        contentViews.setTextViewText(R.id.currentmusic,  "标题—作者");
        String filePath = "https://img.alicdn.com/bao/uploaded/i3/356060330/O1CN01lEWcHx1EJBBU7Wk9v-356060330.jpg_430x430q90.jpg";
        contentViews.setImageViewBitmap(R.id.playtag, getBitmap(filePath));
        notify.contentView = contentViews;

        nm.notify(NOTIFICATION_ID, notify);//调用notify方法后即可显示通知
    }



    @ReactMethod
    public void updatePlaybackState(int currentState) {
        System.out.println("updatePlaybackState");
        int state = (currentState == 1) ? PlaybackStateCompat.STATE_PAUSED : PlaybackStateCompat.STATE_PLAYING;
        //第三个参数必须为1，否则锁屏上面显示的时长会有问题
        stateBuilder.setState(state, 0, 1.0f);
        mMediaSession.setPlaybackState(stateBuilder.build());
        showNotification((currentState == 1) ? false : true);
    }

    @ReactMethod
    public void updateLocMsg(String title, String artist, String album, int duration) {
        System.out.println("updateLocMsg");
        try {
            //同步歌曲信息
            MediaMetadataCompat.Builder md = new MediaMetadataCompat.Builder();
            md.putString(MediaMetadataCompat.METADATA_KEY_TITLE, title);
            md.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, artist);
            md.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, album);
            md.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration);
            md.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, getBitmap("http://img.alicdn.com/imgextra/https://img.alicdn.com/bao/uploaded/i3/356060330/O1CN01lEWcHx1EJBBU7Wk9v-356060330.jpg_430x430q90.jpg"));
            md.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, getBitmap("http://img.alicdn.com/imgextra/https://img.alicdn.com/bao/uploaded/i3/356060330/O1CN01lEWcHx1EJBBU7Wk9v-356060330.jpg_430x430q90.jpg"));
//            md.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, "http://img.alicdn.com/imgextra/https://img.alicdn.com/bao/uploaded/i3/356060330/O1CN01lEWcHx1EJBBU7Wk9v-356060330.jpg_430x430q90.jpg");
            mMediaSession.setMetadata(md.build());
        } catch (Exception e) {
//            LogTool.ex(e);
        }

    }

    public Bitmap getBitmap(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;

            int length = http.getContentLength();

            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();// 关闭流
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }

    @ReactMethod
    public void show(String message, int duration) {
        System.out.println("到这里了吗");
        Toast.makeText(getReactApplicationContext(), message, duration).show();
    }

    private void sendEvent(ReactContext reactContext,
                           String eventName,
                           @Nullable WritableMap params) {
        reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }

    public void onPlayMusic() {
        System.out.println("继续播放");
        WritableMap params = Arguments.createMap();
        params.putString("name", "继续播放");
        sendEvent(getReactApplicationContext(), "playTest", params);

    }

    public void onPauseMusic() {
        System.out.println("暂停播放");
        WritableMap params = Arguments.createMap();
        params.putString("name", "暂停播放");
        sendEvent(getReactApplicationContext(), "playTest", params);

    }

    public void onPlayAndPause() {

        System.out.println("暂停or播放");
        WritableMap params = Arguments.createMap();
        params.putString("name", "暂停or播放");
        sendEvent(getReactApplicationContext(), "playTest", params);
    }

    public void onNextMusic() {
        System.out.println("下一首");
        WritableMap params = Arguments.createMap();
        params.putString("name", "下一首");
        sendEvent(getReactApplicationContext(), "playTest", params);

    }

    public void onPrevMusic() {
        System.out.println("上一首");
        WritableMap params = Arguments.createMap();
        params.putString("name", "上一首");
        sendEvent(getReactApplicationContext(), "playTest", params);
    }

    private MediaSessionCompat.Callback sessionCb = new MediaSessionCompat.Callback() {


        @Override
        public void onPlay() {
            super.onPlay();
            onPlayMusic();

        }

        @Override
        public void onPause() {
            super.onPause();
            onPauseMusic();

        }

        @Override
        public void onSkipToNext() {
            super.onSkipToNext();
            onNextMusic();

        }

        @Override
        public void onSkipToPrevious() {
            super.onSkipToPrevious();
            onPrevMusic();
        }

    };
}


